﻿using System;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace PropertyExpression.ControllableQuery.Test
{
    public static partial class Paging
    {
        
    }

    public static class Paging2
    {
        public static QWriter Rows(QFragment mainQuery, QFragment orderBy, Param<int> start, Param<int> finish)
        {
            return new QWriter().Write(new {mainQuery, orderBy, start, finish}.QFragment(@"
SELECT  *
FROM    (SELECT *,
                ROW_NUMBER() OVER (ORDER BY @orderBy) AS RowNumber
         FROM   (@mainQuery
                ) _
        ) _
WHERE   RowNumber BETWEEN @start AND @finish"));
        }

        public static QWriter Count(QFragment mainQuery)
        {
            return new QWriter().Write(new {mainQuery}.QFragment(@"
SELECT  COUNT(*) AS Value
FROM    (@mainQuery
        ) _
"));
        }

        public static Tuple<QWriter, QWriter> All2(QFragment mainQuery, QFragment orderBy,
            Param<int> start, Param<int> finish)
        {
            return Tuple.Create(Rows(mainQuery, orderBy, start, finish), Count(mainQuery));
        }

        public static QWriter All(QFragment mainQuery, QFragment orderBy, Param<int> start, Param<int> finish)
        {
            return new QWriter().Write(new {mainQuery, orderBy, start, finish}.QFragment(@"
SELECT  *
FROM    (SELECT *,
                ROW_NUMBER() OVER (ORDER BY @orderBy) AS RowNumber
         FROM   (@mainQuery
                ) _
        ) _
WHERE   RowNumber BETWEEN @start AND @finish

SELECT  COUNT(*) AS Value
FROM    (@mainQuery
        ) _"));
        }

        static Paging2()
        {
            RegisterRazorConfiguration();
        }

        private static void RegisterRazorConfiguration([CallerFilePath] string filePath = "")
        {
            RazorConfiguration.Register(filePath, new [] {
                "PropertyExpression.ControllableQuery.Test"
            }, MethodBase.GetCurrentMethod());
        }
    }

    public class Paging<TRows, TCount>
    {
        private readonly TRows rows;
        private readonly TCount count;

        public Paging(TRows rows, TCount count)
        {
            this.rows = rows;
            this.count = count;
        }

        public TRows Rows
        {
            get { return rows; }
        }

        public TCount Count
        {
            get { return count; }
        }
    }
}